<template>
  <div class="loginElement">
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
      <el-form-item label="帐号：" prop="username">
        <el-input v-model="ruleForm.username" @keydown.enter="login"/>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input type="password" v-model="ruleForm.password" @keydown.enter="login"/>
      </el-form-item>
      <el-form-item label="验证码：" prop="code">
        <div style="display: flex; align-items: center;">
          <el-input
              v-model="ruleForm.code"
              @keydown.enter="login"
              style="flex: 1; min-width: 100px; max-width: 250px;"
          />
          <div class="login-code" style="margin-left: 10px; flex-shrink: 0;">
            <img :src="codeUrl" @click="getCode" style="height: 38px; cursor: pointer;"/>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <div style="width: 100%; text-align: center">
      <el-button type="primary" id="btn" @click="login">登录</el-button>
    </div>
  </div>
</template>

<script setup>
import * as menuUtil from "@/util/menuUtil.js";


// 全局服务 & 配置（需通过 app.config.globalProperties 提供或直接导入）
const router = useRouter()
const httpService = inject('httpService')
const util = inject('util')

// 表单数据
const ruleForm = reactive({
  username: 'admin',
  password: '123456',
  code: '',
  randomStr: util.uuid(),
})

// 表单校验规则
const rules = {
  username: [{required: true, message: '请输入帐号', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
  code: [{required: true, message: '请输入验证码', trigger: 'blur'}],
}

// 验证码图片地址
const codeUrl = ref('')

// 表单 DOM 引用
const ruleFormRef = ref()

// 获取验证码
const getCode = () => {
  ruleForm.randomStr = util.uuid()
  httpService.get('/sys-login/getCode', {
    randomStr: ruleForm.randomStr,
  }).then(res => {
    codeUrl.value = res
  })
}

// 登录逻辑
const login = () => {
  ruleFormRef.value.validate(valid => {
    if (valid) {
      httpService.post('/sys-login/login', ruleForm)
          .then(res => {
            util.setLoginInfo(res) // 保存用户信息
            //添加路由
            menuUtil.createDynamicRoute()
            router.push({path: '/'})
          })
          .catch(() => {
            getCode()
          })
    }
  })
}

// 页面加载自动加载验证码
onMounted(() => {
  getCode()
})
</script>

<style scoped>
.login-code {
  height: 50px;
  margin-left: 10px;
  cursor: pointer;
}
</style>
